package com.lse_api.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lse_api.utils.Status;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * spring security 自定义错误返回信息
 *
 * @author 祁雪
 */
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    public static Status status;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(HttpStatus.OK.value());
        if (status == null) {
            status = Status.error(accessDeniedException.getMessage());
        }
        response.getWriter().write(new ObjectMapper().writeValueAsString(status));
        response.getWriter().flush();
    }

}
